package com.gmail.at.controller;

import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.gmail.at.model.Passenger;
import com.gmail.at.model.Schedule;
import com.gmail.at.model.Station;
import com.gmail.at.model.Ticket;
import com.gmail.at.service.PassengerService;
import com.gmail.at.service.ScheduleService;
import com.gmail.at.service.StationService;
import com.gmail.at.service.TicketService;
import com.gmail.at.service.TrainService;

@Controller
@RequestMapping("/")
public class MainController {

	final Logger logger = LoggerFactory.getLogger(MainController.class);

	@Autowired
	private ScheduleService scheduleService;

	@Autowired
	private StationService stationService;

	@Autowired
	private TrainService trainService;

	@Autowired
	private TicketService ticketService;

	@Autowired
	private PassengerService passengerService;

	@Autowired
	MessageSource messageSource;

	@RequestMapping(method = RequestMethod.GET)
	public String index(Model uiModel) {
		Schedule schedule = new Schedule();
		uiModel.addAttribute("schedule", schedule);
		return "main/index";
	}

	@RequestMapping(method = RequestMethod.GET, params = "auto")
	public @ResponseBody
	List<Station> auto(Model uiModel) {
		logger.info("Listing stations");
		List<Station> stations = stationService.findAll();
		return stations;
	}

	@RequestMapping(value = "/", method = RequestMethod.POST)
	public @ResponseBody
	List<Schedule> searchSchedules(@Valid Schedule schedule,
			BindingResult bindingResult, Model uiModel,
			HttpServletRequest httpServletRequest,
			RedirectAttributes redirectAttributes, Locale locale) {
		DateTime departure = null;
		try {
			DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
			departure = formatter.parseDateTime(schedule.getSearchDate());
		} catch (IllegalArgumentException e){
			return null;
		}
		List<Schedule> schedules = scheduleService.searchSchedule(
				schedule.getStation1(), schedule.getStation2(), departure);
		logger.info("Found schedules" + schedules.size());
		return schedules;
	}

	@RequestMapping(params = "tickets", method = RequestMethod.GET)
	public String ticket(Model uiModel) {
		User user = null;
		try {
			user = (User) SecurityContextHolder.getContext()
					.getAuthentication().getPrincipal();
		} catch (Exception e) {
			return "/train-system/";
		}
		Passenger passenger = null;
		for (Passenger p : passengerService.findAll()) {
			if (p.getLogin().equals(user.getUsername())) {
				passenger = p;
			}
		}
		uiModel.addAttribute("tickets", passenger.getTickets());
		return "main/ticketsList";
	}

	@RequestMapping(value = "/{scheduleID}", method = RequestMethod.GET)
	public @ResponseBody
	String buyTicket(@PathVariable("scheduleID") Integer id, Model uiModel) {
		Schedule schedule = scheduleService.findById(id);
		if (schedule == null) {
			return "This train was not found";
		}
		return (ticketService.buy(schedule));
	}
	
	@RequestMapping(value = "/{ticketID}", params = "delete", method = RequestMethod.GET)
	public @ResponseBody
	String sellTicket(@PathVariable("ticketID") Integer id, Model uiModel) {
		Ticket ticket = ticketService.findById(id);
		if (ticket == null) {
			return "This ticket was not found";
		}
		return (ticketService.sell(ticket));
	}
}
